package com.dq.wx.pay.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信支付 WxPayService 配置类
 * @author cf
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
//@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration {

  /**
   * 微信支付开发 参数配置类
   */
  @Autowired
  private WxPayProperties wxPayProperties;

  /**
   * 微信支付: WxPayService
   * @return
   */
  @Bean
  @ConditionalOnMissingBean
  public WxPayService wxService() {
    WxPayConfig payConfig = new WxPayConfig();
    payConfig.setAppId(StringUtils.trimToNull(wxPayProperties.getAppid()));
    payConfig.setMchId(StringUtils.trimToNull(wxPayProperties.getMchid()));
    payConfig.setMchKey(StringUtils.trimToNull(wxPayProperties.getMchKey()));
    payConfig.setKeyPath(StringUtils.trimToNull(wxPayProperties.getKeyPath()));

    /// sub开头的两个参数属于服务商模式使用的，如果是普通模式，请不要配置这两个参数，最好从配置文件中移除相关项
//    payConfig.setSubAppId(StringUtils.trimToNull(wxPayProperties.getSubAppId()));
//    payConfig.setSubMchId(StringUtils.trimToNull(wxPayProperties.getSubMchId()));

    // 可以指定是否使用沙箱环境
    payConfig.setUseSandboxEnv(false);

    WxPayService wxPayService = new WxPayServiceImpl();
    wxPayService.setConfig(payConfig);
    return wxPayService;
  }

}
